const {pathResolve} = require('./utils');
const fs = require('fs');
const os = require('os');
const {app, BrowserWindow, ipcMain, dialog} = require('electron');
const config = require('./config');
const GitFun = require('./gitFun');
const FileFun = require('./fileFun');
const htmlPage = pathResolve(__dirname, '../html');
let localGitStorePath = '';
let fileFun;
let gitfun;
let gitUrl;
let options;
let setWin;

async function main() {
  let dirFlag;
  options = await config.getConfig('config');
  if (options.gitDir) {
    dirFlag = await FileFun.getState(options.gitDir);
    dirFlag = dirFlag && dirFlag.isDirectory();
  }
  if (!dirFlag || !options.gitUrl || !options.gitPath || !options.gitDir) {
    createInputWindow();
  } else {
    localGitStorePath = options.gitDir;
    fileFun = new FileFun(localGitStorePath);
    gitfun = new GitFun(options.gitPath, localGitStorePath);
    createMainWindow();
    gitUrl = options.gitUrl;
  }
}

function createMainWindow() {
  // 创建浏览器窗口
  let win = new BrowserWindow({
    width: 1200,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
    show: false,
  });
  win.once('ready-to-show', () => {
    if (setWin) setWin.close();
    win.show();
  });

  win.webContents.openDevTools();

  // 加载index.html文件
  win.loadFile(htmlPage + '/index.html');

  ipcMain.on('queyMenuList', async (event, params) => {
    if (!gitUrl) return;
    const data = await fileFun.readFileList();
    if (data) {
      win.webContents.send('sendMenuList', data);
    }
  });

  ipcMain.on('queryFileData', async (event, params) => {
    if (!gitUrl || !params.path) return;
    const data = await fileFun.readFile(params.path);
    if (data) {
      win.webContents.send('sendFileData', data);
    }
  });

  ipcMain.on('sendFileData', async (event, params) => {
    if (!gitUrl || !params.path) return;
    const data = await fileFun.writeFile(params.path, params.data);
    if (data) {
      win.webContents.send('getSaveDataStatus', data);
    }
  });

  ipcMain.on('reportNote', async (event, params) => {
    console.log('report Note');
    let flag = await FileFun.getState(localGitStorePath + '/.git');
    if (!flag || !flag.isDirectory()) {
      console.log('not dir, will be clone store');
      win.webContents.send('getReportNoteStatus', 404);
      return;
    }
    flag = await gitfun.reportData();
    win.webContents.send('getReportNoteStatus', flag);
  });

  ipcMain.on('cloneStore', async (event, params) => {
    console.log('clone Store');
    if (!gitUrl) {
      console.log('clone Store but not gitUrl');
      win.webContents.send('getCloneStoreStatus', null);
    }
    const fileFlag = await gitfun.clone(gitUrl);
    if (!fileFlag) {
      win.webContents.send('getCloneStoreStatus', null);
      return;
    }
    win.webContents.send('getCloneStoreStatus', true);
  });

  ipcMain.on('createFile', async (event, params) => {
    console.log('create File');
    const fileName = new Date().getTime() + '';
    const filePath = pathResolve(localGitStorePath, fileName + '.txt');
    const fileFlag = await fileFun.writeFile(filePath, '');
    if (!fileFlag) {
      win.webContents.send('getCreateFileStatus', null);
      return;
    }
    win.webContents.send('getCreateFileStatus', filePath);
  });

}

function createInputWindow() {
  setWin = new BrowserWindow({
    width: 400,
    height: 600,
    resizable: false,
    maximizable: false,
    webPreferences: {
      nodeIntegration: true,
    },
    show: false,
  });

  setWin.once('ready-to-show', () => {
    setWin.show();
  });
  setWin.loadFile(htmlPage + '/input.html');
  setWin.webContents.openDevTools();
  ipcMain.on('queryConfigData', () => {
    const obj = {
      gitPath: options.gitPath,
      gitUrl: options.gitUrl,
      gitDir: options.gitDir || os.homedir() + '/.kkNote'
    };
    setWin.webContents.send('getConfigData', obj);
  });

  ipcMain.on('chooseDir', () => {
    dialog.showOpenDialog({
      title: '选择Gti本地厂库',
      defaultPath: os.homedir() + '/',
      buttonLabel: '选择',
      properties: ['openDirectory', 'createDirectory']
    }).then(res => {
      console.log('success', res);
      if (res.filePaths[0]) {
        setWin.webContents.send('getDirPath', res.filePaths[0]);
      }
    }).catch(e => {
      console.log('choose dir fail', e);
    });
  });

  ipcMain.on('setConfig', async (event, params) => {
    const data = params.data;
    const flag = await config.updateConfig(Object.assign(options, data));
    if (!flag) {
      setWin.webContents.send('getUpdateStatus', '配置文件更新失败');
      return;
    }
    try {
      const flag = await FileFun.getState(data.gitDir);
      if (!flag || !flag.isDirectory()) fs.mkdirSync(data.gitDir);
    } catch (e) {
      console.log('创建对应的本地厂库文件夹失败', e);
      setWin.webContents.send('getUpdateStatus', '创建对应的本地厂库文件夹失败');
      return;
    }
    setWin.webContents.send('getUpdateStatus', 0);
    setTimeout(() => {
      main();
    }, 500);
  });
}

app.on('ready', main);
